package com.moxingzhegroup.activity;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.WriterException;
import com.moxingzhegroup.Constants;
import com.moxingzhegroup.R;
import com.moxingzhegroup.base.BaseActivity;
import com.moxingzhegroup.entity.api.Result;
import com.moxingzhegroup.util.CodeUtils;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.PushAgent;
import com.umeng.message.api.UPushRegisterCallback;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.Objects;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 打开APP首先会显示的设备的MAC地址二维码界面
 *
 * @author LiaoRun
 */
@SuppressWarnings("AlibabaAvoidUseTimer")
public class QrCodeActivity extends BaseActivity {

    private static final String TAG = QrCodeActivity.class.getName();
    private ImageView mQrCodeImageView;
    private TextView mWaitTip;
    private Timer jumpToMainActivityTimer;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_qr_code);

        // 后台获取设备是否绑定，如果绑定了就直接跳转到主界面

        Button clearCacheBtn = findViewById(R.id.clear_cache_btn);
        if (clearCacheBtn != null) {
            clearCacheBtn.requestFocus();
            clearCacheBtn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 弹出一个弹框
                    clickManyTimesImpl();
                }
            });
        }

        mQrCodeImageView = findViewById(R.id.qr_code_img);
        mWaitTip = findViewById(R.id.wait_tip);

        // 获取友盟的deviceToken，当作设备的唯一标识，和店铺对应
        initUmeng();
    }

    /**
     * 上次点击时间
     */
    long time = 0;

    /**
     * 当前点击次数
     */
    Integer count = 1;

    /**
     * 打开删除缓存界面需要连续点击的次数
     */
    private static final Integer NEED_CLICK_TIMES = 3;


    /**
     * 连续点击允许的最大间隔
     */
    private static final Integer MAXIMUM_CLICK_INTERVAL = 1000;

    /**
     * 作者:赵星海
     * 时间:2021/3/15 4:58
     * 用途:连续点击五次退出
     * 在点击事件里调用即可
     **/
    private void clickManyTimesImpl() {
        long timeNew = System.currentTimeMillis();
        //连续点击间隔，每次点击间隔不能大于1秒
        if ((timeNew - time) < MAXIMUM_CLICK_INTERVAL) {
            count += 1;
        } else {
            count = 1;
        }
        time = timeNew;
        // 检查点击次数是否达到需要
        if (count >= NEED_CLICK_TIMES) {
            //触发后五连点之后需要做的事情
            // 弹出弹窗
            showDeleteCacheDialog();

            // 停止跳转到主界面
            jumpToMainActivityTimer.cancel();
        }
    }


    @SuppressWarnings("AlibabaMethodTooLong")
    private void initUmeng() {
        //初始化组件化基础库, 所有友盟业务SDK都必须调用此初始化接口。
        UMConfigure.init(QrCodeActivity.this, Constants.APP_KEY, "Umeng", UMConfigure.DEVICE_TYPE_PHONE, Constants.UMENG_MESSAGE_SECRET);

        //获取消息推送代理示例
        PushAgent mPushAgent = PushAgent.getInstance(QrCodeActivity.this);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new UPushRegisterCallback() {
            @SuppressLint("SetTextI18n")
            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回deviceToken deviceToken是推送消息的唯一标志
                Log.d(TAG, "注册成功：deviceToken：--------> " + deviceToken);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mWaitTip.setText("注册成功：deviceToken：--------> " + deviceToken);
                    }
                });

                String url = Constants.BASE_URL + "/television/check_binding";
                OkHttpClient okHttpClient = new OkHttpClient();

                HttpUrl.Builder builder = Objects.requireNonNull(HttpUrl.parse(url)).newBuilder();

                builder.addQueryParameter("deviceToken", deviceToken);


                Request request = new Request.Builder()
                        .get()
                        .url(builder.build())
                        .build();


                okHttpClient.newCall(request).enqueue(new Callback() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void onFailure(@NonNull Call call, @NonNull IOException e) {

                        Log.d(TAG, "onFailure: 查询是否设备已经绑定失败" + e.getMessage());

                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                mWaitTip.setText("onFailure: 查询是否设备已经绑定失败" + e.getMessage());

                                // 3 秒后直接跳转到广告播放界面
                                jumpToMainActivity(3);
                            }
                        });
                    }

                    @Override
                    public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {

                        if (response.isSuccessful()) {
                            Type type = new TypeToken<Result<Boolean>>() {
                            }.getType();

                            assert response.body() != null;
                            Result<Boolean> result = new Gson().fromJson(response.body().string(), type);

                            Log.w(TAG, "onResponse: 是否绑定了二维码：" + result.getData());
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mWaitTip.setText("onResponse: 是否绑定了二维码：" + result.getData());
                                }
                            });

                            if (result.getData()) {
                                // 已经绑定
                                // 跳转到主界面
                                Intent intent = new Intent(QrCodeActivity.this, MainActivity.class);

                                startActivityForResult(intent, MainActivity.class.hashCode());
                            } else {
                                showQrCode(deviceToken);
                            }
                        } else {
                            Log.d(TAG, "onResponse: " + response.message());
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    mWaitTip.setText("onResponse: " + response.message());
                                }
                            });
                            Toast.makeText(getApplicationContext(), response.message(), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }

            @SuppressLint("SetTextI18n")
            @Override
            public void onFailure(String s, String s1) {
                Log.e(TAG, "注册失败：--------> " + "s:" + s + ", s1:" + s1);

                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mWaitTip.setText("注册失败：--------> " + "s:" + s + ", s1:" + s1);
                    }
                });
            }
        });
    }

    @SuppressWarnings("AlibabaAvoidUseTimer")
    @SuppressLint("SetTextI18n")
    private void showQrCode(String deviceToken) {
        // 将 deviceToken 生成二维码显示


        Bitmap logo = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

        final Bitmap bitmap;
        try {
            bitmap = CodeUtils.createCode(getApplicationContext(), deviceToken, logo);
        } catch (WriterException e) {
            e.printStackTrace();
            Log.d(TAG, "showQrCode: 创建二维码失败，直接跳转到Main" + e.getMessage());

            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    mWaitTip.setText("showQrCode: 创建二维码失败，直接跳转到Main" + e.getMessage());
                }
            });

            // 跳转到主界面
            Intent intent = new Intent(QrCodeActivity.this, MainActivity.class);

            startActivityForResult(intent, MainActivity.class.hashCode());
            return;
        }


        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mWaitTip.setVisibility(View.INVISIBLE);
                mQrCodeImageView.setImageBitmap(bitmap);
            }
        });

        // 显示从后台获取的显示描述后调转到主界面
        jumpToMainActivity(10);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == MainActivity.class.hashCode()) {

            Log.d(TAG, "onActivityResult: 直接退出应用成功");
            finish();
        } else {
            Log.d(TAG, "onActivityResult: 没能直接退出应用成功");
        }
    }


    /**
     * 弹出确认删除本地缓存的弹窗
     */
    public void showDeleteCacheDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(QrCodeActivity.this);
        builder.setTitle("确认弹框");
        StringBuilder stringBuilder = new StringBuilder("你确认要删除本地缓存嘛？删除后需要从服务器重新下载所有的视频!你将删除的视频有");
        // 获取本地存储视频的文件夹
        File file = new File(Constants.getVideoPath());

        if (file.exists()) {
            // 如果该文件夹存在，获取文件夹下的所有文件
            File[] listFiles = file.listFiles();

            if (listFiles != null) {
                for (File listFile : listFiles) {
                    stringBuilder.append("<").append(listFile.getName()).append(">,");
                }
            }
        }

        stringBuilder.append("你当前设备的安卓版本号为：").append(Build.VERSION.SDK_INT);

        builder.setPositiveButton("立即删除", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                // 删除本地缓存

                // 获取本地存储视频的文件夹
                File file = new File(Constants.getVideoPath());

                if (file.exists()) {
                    // 如果该文件夹存在，获取文件夹下的所有文件
                    File[] listFiles = file.listFiles();

                    if (listFiles != null) {
                        // 删除该存储视频的文件夹下的所有文件
                        for (File listFile : listFiles) {
                            if (!listFile.delete()) {
                                Toast.makeText(QrCodeActivity.this, "删除一个文件失败，文件名：" + listFile.getName(), Toast.LENGTH_SHORT).show();
                            }
                        }

                        Toast.makeText(QrCodeActivity.this, "删除所有缓存成功", Toast.LENGTH_SHORT).show();

                        jumpToMainActivity(5);
                        return;
                    }
                }

                Toast.makeText(QrCodeActivity.this, "本地没有缓存可以删除", Toast.LENGTH_SHORT).show();

                jumpToMainActivity(5);
            }
        });
        builder.setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
            @SuppressWarnings("AlibabaAvoidUseTimer")
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();

                jumpToMainActivity(5);
            }
        });

        builder.setMessage(stringBuilder.toString());

        builder.create().show();
    }

    /**
     * 5秒后跳转到主界面
     */
    private void jumpToMainActivity(long delayBySecond) {

        // 停掉原来的
        if (jumpToMainActivityTimer != null) {
            jumpToMainActivityTimer.cancel();
        }

        // 创建一个新的
        jumpToMainActivityTimer = new Timer();

        jumpToMainActivityTimer.schedule(new TimerTask() {
            @Override
            public void run() {
                // 继续跳转
                // 跳转到主界面
                Intent intent = new Intent(QrCodeActivity.this, MainActivity.class);

                startActivityForResult(intent, MainActivity.class.hashCode());
            }
        }, delayBySecond * 1000);
    }
}


